package com.sunelec.controller;

import com.sunelec.mapper.InverterMapper;
import com.sunelec.mapper.PowerMapper;
import com.sunelec.mapper.RelationshipMapper;
import com.sunelec.mapper.UsersMapper;
import com.sunelec.pojo.*;
import com.sunelec.service.UserService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @Author: 郑明利
 * @Description: 用户登录注册Controller
 * @Date: Create in 13:07 2018/04/17
 * @Modified By:
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RelationshipMapper relationshipMapper;

    @Autowired
    private PowerMapper powerMapper;

    @Autowired
    private InverterMapper inverterMapper;

    ArrayList<PowerList> powerLists = new ArrayList<PowerList>();

    PowerCenter powerCenter = new PowerCenter();

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    /**
     * 登陆数据提交界面
     */
    //用户登录
    @RequestMapping("/userLogin")
    public String userLogin(String username, String password, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
        String status = "";
        try{
            Users users = new Users();
            status = request.getParameter("login_status");
            if(status.equals("reload")){
                users = (Users)session.getAttribute("users");
                password = users.getPassword();
                username = users.getUsersname();
            }
        }catch (Exception e){

        }
        Users users = new Users();
        SunElecResult result = null;
        session.setAttribute("username",username);
        try {
            result = userService.userLogin(username, password, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ((int)result.getStatus() == 200){
            //根据用户等级获取到其下所有的电站二级账号关联有三级账号，一级账号浏览所有
            if(usersMapper.selectByUsername(username).getType() == 3){
                //三级权限（一个账号可以拥有多个电站）
                // 根据username去relationship表中查找对应powerId列表
                if(session.getAttribute("powerLists")!=null){
                    session.removeAttribute("powerLists");
                }
                powerLists.clear();
                PowerList powerL1 = new PowerList();
                powerLists.add(0,powerL1);
                PowerCenter powerCenter = this.getPowerCenterInfo(username,session);
                model.addAttribute("powerCenter",powerCenter);
                users.setType(3);
            }else if(usersMapper.selectByUsername(username).getType() == 2){
                if(session.getAttribute("powerLists")!=null){
                    session.removeAttribute("powerLists");
                }
                powerLists.clear();
                //二级权限（一个账号关联有一个或多个三级账号）
                //先查找这个用户下的所有三级账号
                PowerList powerL1 = new PowerList();
                powerLists.add(0,powerL1);
                List<Relationship> powerRelationList = relationshipMapper.selectByUserLevel2(username);
                PowerCenter powerCenter = new PowerCenter();
                int current_power=0; int installCapacity = 0;float daily_elec=0; float month_elec=0;
                float year_elec=0; float all_elec=0; int runing_normal=0;
                int runing_excpetion=0; int runing_warning=0;
                double co2=0; double so2=0; double tree=0;
                for(int i=0;i<powerRelationList.size();i++){
                    String user3 = powerRelationList.get(i).getLevel3user3();
                    PowerCenter powerCenters = this.getPowerCenterInfo(user3,session);
                    current_power = powerCenters.getCurrent_power();
                    installCapacity = Integer.parseInt(powerCenters.getInstallCapacity());
                    daily_elec = powerCenters.getDaily_elec();
                    month_elec = powerCenters.getMonth_elec();
                    year_elec = powerCenters.getYear_elec();
                    all_elec = powerCenters.getAll_elec();
                    runing_normal =powerCenters.getRuning_normal();
                    runing_excpetion = powerCenters.getRuning_excpetion();
                    runing_warning = powerCenters.getRuning_warning();
                    co2 = (double)Math.round(powerCenters.getCo2()*100)/100;
                    so2 = (double)Math.round(powerCenters.getSo2()*100)/100;
                    tree = (double)Math.round(powerCenters.getTree()*100)/100;
                }
                powerCenter.setCurrent_power(current_power);
                powerCenter.setInstallCapacity(installCapacity+"");
                powerCenter.setDaily_elec(daily_elec);
                powerCenter.setMonth_elec(month_elec);
                powerCenter.setYear_elec(year_elec);
                powerCenter.setAll_elec(all_elec);
                powerCenter.setRuning_normal(runing_normal);
                powerCenter.setRuning_excpetion(runing_excpetion);
                powerCenter.setRuning_warning(runing_warning);
                powerCenter.setCo2(co2);
                powerCenter.setSo2(so2);
                powerCenter.setTree(tree);
                users.setType(2);
                model.addAttribute("powerCenter",powerCenter);
            }else if(usersMapper.selectByUsername(username).getType() == 1){
                if(session.getAttribute("powerLists")!=null){
                    session.removeAttribute("powerLists");
                }
                powerLists.clear();
                PowerList powerL1 = new PowerList();
                powerLists.add(0,powerL1);
                //一级账户，查看所有
                //1、查找所有电站列表
                List<Power> power = this.getAllPower();
                //2、遍历power取powerId
                PowerList powerList = new PowerList();
                //产能中心
                int current_power = 0;
                int install_capacity = 0;
                float daily_elec = 0;
                float month_elec =0;
                float year_elec =0;
                float all_elec =0;
                int runing_normal = 0;
                int runing_excpetion = 0;
                int runing_warning = 0;
                int runing_num = 0;

                for (int i=0;i<power.size();i++){
                    //用powerId
                    powerList = this.getPowerInfoByPowerId(power.get(i).getPowerId());
                    if(powerLists.size()!=0){
                        powerLists.add(powerLists.size(),powerList);
                    }
                }
                runing_num=powerLists.size()-1;
                for(int j=1;j<powerLists.size();j++){
                    current_power += powerLists.get(j).getCurrent_power();
                    try{
                        install_capacity += Integer.parseInt(powerLists.get(j).getInstallCapacity());
                    }catch (NumberFormatException e){
                        install_capacity += 0;
                    }
                    daily_elec += powerLists.get(j).getDaily_electricity();
                    month_elec += powerLists.get(j).getMonth_elec();
                    year_elec += powerLists.get(j).getYear_elec();
                    all_elec += powerLists.get(j).getAll_elec();
                    if(powerLists.get(j).getRuning_id() == 1){
                        runing_normal++;
                    }else if(powerLists.get(j).getRuning_id() == 2){
                        runing_excpetion++;
                    } else if (powerLists.get(j).getRuning_id() == 3) {
                        runing_warning++;
                    }
                    //电站状态;每发一度电，就节约了0.328千克的标准煤，同时减少二氧化碳排放0.997千克，二氧化硫排放0.003千克
                    double co2 = (double)Math.round((all_elec/1000) * 0.997*100)/100;
                    double so2 = (double)Math.round((all_elec/1000) * 0.003*100)/100;
                    double mei = (double)Math.round((all_elec/1000) * 0.328*100)/100;
                    double tree_1 = ((all_elec/1000) * 0.997)/365;
                    double tree = (double)Math.round(tree_1 * 100)/100;
                    powerCenter.setCurrent_power(current_power);
                    powerCenter.setInstallCapacity(install_capacity+"");
                    powerCenter.setDaily_elec(daily_elec);
                    powerCenter.setMonth_elec(month_elec);
                    powerCenter.setYear_elec(year_elec);
                    powerCenter.setAll_elec(all_elec);
                    powerCenter.setRuning_num(runing_num);
                    powerCenter.setRuning_normal(runing_normal);
                    powerCenter.setRuning_excpetion(runing_excpetion);
                    powerCenter.setRuning_warning(runing_warning);
                    powerCenter.setCo2(co2);
                    powerCenter.setSo2(so2);
                    powerCenter.setTree(tree);
                    model.addAttribute("powerCenter",powerCenter);
                }
                //电站列表
                session.setAttribute("powerLists",powerLists);
                users.setType(1);
            }
            users.setUsersname(username);
            users.setPassword(password);
            session.setAttribute("users",users);
            return "/informationCenter";
        } else{
            model.addAttribute("msg",result.getMsg());
            return "/login";
        }
    }

    //获得所有的电站基础信息
    public List<Power> getAllPower(){
        List<Power> power = powerMapper.selectAllPower();
        return power;
    }

    //根据powerId获取该电站下的所有信息
    public PowerList getPowerInfoByPowerId(String powerId){
        PowerList powerList = new PowerList();
        //按照powerId
        //根据powerId去power表中获取当前电站的采集器SN号（注意：SN号可能为一组值，我们需要进行判断分割）
        //分割依据：录入时，我们将采集器的SN号使用空格进行分割
        Power power = powerMapper.selectByPrimaryKey(powerId);
        String powerSN = power.getPowerSn();
        String[] powerSNArray = null;
        if(powerSN !=null){
            //目前SN号仅对应逆变器，还未对气象站，电表进行统计，不需要额外判断
            powerSNArray = powerSN.split(",");
        }
        //根据得到的powerSN的数组循环得到每个对应的inverter表中的数据
        List<Inverter> inverterList = null;
        for(int i=0;i<powerSNArray.length;i++){
            inverterList = inverterMapper.selectByPowerSN(powerSNArray[i]);
        }
        //产能中心数据
        //当前功率（各个逆变器功率之和）
        //当前年月日
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH )+1;
        int day = cal.get(Calendar.DATE);
        String month_date = year + "-" + month + "-" + day;

        int current_power = 0;
        for (int i=0;i<powerSNArray.length;i++){
            try{
                current_power += inverterMapper.selectCurrentPower(powerSNArray[i],month_date);
            }catch (Exception e) {
                current_power += 0;
            }
        }
        //总装机容量
        String install_capacity = power.getInstallCapacity();
        //日发电量
        float daily_elec = 0;

        for (int i=0;i<powerSNArray.length;i++){
            daily_elec += inverterMapper.selectDailyElec(powerSNArray[i],month_date);
        }
        //月发电量
        float month_elec = 0;
        //开始
        String month_start =  year + "-" + month + "-1";
        //结束
        String month_end =  year + "-" + month + "-31";
        for (int i=0;i<powerSNArray.length;i++){
            month_elec += inverterMapper.selectMonthElec(powerSNArray[i],month_start,month_end);
        }
        //年电量
        float year_elec = 0;
        for (int i=0;i<powerSNArray.length;i++){
            year_elec += inverterMapper.selectMonthElec(powerSNArray[i],year+"-01-01",year+"-12-31");
        }
        //累计发电量
        float all_elec =0;
        for (int i=0;i<powerSNArray.length;i++){
            all_elec += inverterMapper.selectAllElec(powerSNArray[i]);
        }
        //电站列表
        //电站状态
        int runing_id = power.getRuningId();

        //发电趋势格式[0, 16, 30, 37, 65, 30, 0]
        // 获得4点、8点、12点、16点、20点、24点的当前功率，判断为空就为零  当前电站下所有电站的功率之和
        int[] power_trend = {0,0,0,0,0,0};//数组:多个电站下有多个采集器
        for (int i=0;i<6;i++) {
            for (int j=0;j<powerSNArray.length;j++){
                String time_info = ":00:00";
                int time_num1 = i*4;
                int time_num2 = (i+1)*4;
                String time_start = time_num1 + time_info;
                String time_end = time_num2 + time_info;
                power_trend[i] += inverterMapper.selectSumCurrentPower(powerSNArray[j],month_date,time_start,time_end);
            }
        }
        JSONArray jsonarray = JSONArray.fromObject(power_trend);
        powerList.setPowerId(powerId);
        powerList.setPowerName(power.getPowerName());
        powerList.setPowerLocal(power.getPowerLocal());
        powerList.setRuning_id(runing_id);
        powerList.setInstallCapacity(install_capacity);
        powerList.setUserInfo(power.getOwn());
        powerList.setDaily_electricity(daily_elec);
        powerList.setCurrent_power(current_power);
        powerList.setMonth_elec(month_elec);
        powerList.setYear_elec(year_elec);
        powerList.setAll_elec(all_elec);
        powerList.setUpdate_date(month_date);
        powerList.setJsonarray(jsonarray);

        return powerList;
    }

    public PowerCenter getPowerCenterInfo(String username,HttpSession session){
        List<Relationship> powerRelationList = relationshipMapper.selectByUserLevel3(username);
        //遍历列表，取powerId，进行具体数据查询
        PowerList powerList = new PowerList();
        for(int i=0;i<powerRelationList.size();i++){
            powerList = this.getPowerInfoByPowerId(powerRelationList.get(i).getPowerId());
            if(powerLists.size()!=0){
                powerLists.add(powerLists.size(),powerList);
            }
        }
        //三级账号下的总数据
        //产能中心
        int current_power = 0;
        int install_capacity = 0;
        float daily_elec = 0;
        float month_elec =0;
        float year_elec =0;
        float all_elec =0;
        int runing_normal = 0;
        int runing_excpetion = 0;
        int runing_warning = 0;
        int runing_num = powerLists.size()-1;
        for(int i=1;i<powerLists.size();i++){
            current_power += powerLists.get(i).getCurrent_power();
            try{
                install_capacity += Integer.parseInt(powerLists.get(i).getInstallCapacity());
            }catch (NumberFormatException e){
                install_capacity += 0;
            }
            daily_elec += powerLists.get(i).getDaily_electricity();
            month_elec += powerLists.get(i).getMonth_elec();
            year_elec += powerLists.get(i).getYear_elec();
            all_elec += powerLists.get(i).getAll_elec();
            //电站状态;
            if(powerLists.get(i).getRuning_id() == 1){
                runing_normal++;
            }else if(powerLists.get(i).getRuning_id() == 2){
                runing_excpetion++;
            } else if (powerLists.get(i).getRuning_id() == 3) {
                runing_warning++;
            }
        }
        //电站状态;每发一度电，就节约了0.328千克的标准煤，同时减少二氧化碳排放0.997千克，二氧化硫排放0.003千克
        int power_num = powerRelationList.size();
        double co2 = (double)Math.round((all_elec/1000) * 0.997*100)/100;
        double so2 = (double)Math.round((all_elec/1000) * 0.003*100)/100;
        double mei = (double)Math.round((all_elec/1000) * 0.328*100)/100;
        double tree_1 = ((all_elec/1000) * 0.997)/365;
        double tree = (double)Math.round(tree_1 * 100)/100;
        powerCenter.setCurrent_power(current_power);
        powerCenter.setInstallCapacity(install_capacity+"");
        powerCenter.setDaily_elec(daily_elec);
        powerCenter.setMonth_elec(month_elec);
        powerCenter.setYear_elec(year_elec);
        powerCenter.setAll_elec(all_elec);
        powerCenter.setRuning_num(runing_num);
        powerCenter.setRuning_normal(runing_normal);
        powerCenter.setRuning_excpetion(runing_excpetion);
        powerCenter.setRuning_warning(runing_warning);
        powerCenter.setCo2(co2);
        powerCenter.setSo2(so2);
        powerCenter.setTree(tree);
        //电站列表
        session.setAttribute("powerLists",powerLists);
        return powerCenter;
    }
}
